package com.baize.baizeapp.test.album

import android.content.Context
import android.content.Intent
import android.media.ThumbnailUtils
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baize.baizeapp.App
import com.baize.baizeapp.R
import com.bumptech.glide.Glide
import kotlinx.coroutines.*
import java.io.File
import java.util.*
import kotlin.collections.ArrayList


class AlbumActivity : AppCompatActivity() {
    companion object {
        fun open(context: Context) {
            context.startActivity(
                Intent(context, AlbumActivity::class.java)
            )
        }
    }

    private val IMAGE_PROJECTION = arrayOf(
        MediaStore.Images.Media.DISPLAY_NAME,
        MediaStore.Images.Media.DATA,
        MediaStore.Images.Media.DATE_MODIFIED,
        MediaStore.Images.Media.WIDTH,
        MediaStore.Images.Media.HEIGHT,
        MediaStore.Images.Media.MIME_TYPE
    )

    private val VIDEO_PROJECTION = arrayOf(
        MediaStore.Video.Thumbnails._ID,
        MediaStore.Video.Thumbnails.DATA,
        MediaStore.Video.Media.DURATION,
        MediaStore.Video.Media.SIZE,
        MediaStore.Video.Media.DISPLAY_NAME,
        MediaStore.Video.Media.DATE_MODIFIED
    )

    lateinit var rvAlbum: RecyclerView
    var albumAdapter = AlbumAdapter()

    var queryTask: Job? = null
    private val imageFolders = ArrayList<ImageFolder>()   //所有的图片文件夹

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_album)
        rvAlbum = findViewById<RecyclerView>(R.id.rvAlbum)
        rvAlbum.apply {
            layoutManager =
                GridLayoutManager(this@AlbumActivity, 4, GridLayoutManager.VERTICAL, false)
            adapter = albumAdapter
        }
//        query()
//        queryVideo()
//        queryImageAndVideo()
        queryImgAndVideo()
    }

    fun queryImgAndVideo() {
        val allImages = ArrayList<ImageItem>()
        // 查询图片
        val resolverImageCursor = contentResolver.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            IMAGE_PROJECTION,
            MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
            arrayOf("image/jpeg", "image/png"),
            MediaStore.Images.Media.DATE_MODIFIED + " DESC"
        )
        resolverImageCursor?.use { cursor ->
            while (cursor.moveToNext()) {
                //查询数据
                val imageName =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME))
                val imagePath =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
                val imageDate =
                    cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED))
                val imageWidth =
                    cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH))
                val imageHeight =
                    cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT))
                val imageMimeType =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE))
                if (imageWidth == 0 || imageHeight == 0) {
                    continue
                }
                //封装实体
                val imageItem = ImageItem()
                imageItem.type = 0
                imageItem.name = imageName ?: ""
                imageItem.path = imagePath ?: ""
                imageItem.width = imageWidth
                imageItem.height = imageHeight
                imageItem.imageModifyDate = imageDate
                allImages.add(imageItem)

            }
        }
        resolverImageCursor?.close()

        //查询视频
        var resolverVideoCursor = App.getInstance().getContentResolver().query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            VIDEO_PROJECTION,
            MediaStore.Video.Media.MIME_TYPE + "=?",
            arrayOf("video/mp4"),
            MediaStore.Video.Media.DATE_MODIFIED + " desc"
        )
        val videoList = ArrayList<ImageItem>()
        resolverVideoCursor?.use { cursor ->
            cursor.moveToFirst()
            while (cursor.moveToNext()) {
                val videoId = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID))
                val path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA))
                val duration =
                    cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media.DURATION))
                var size =
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.SIZE)) / 1024 //大小：kb
                if (size < 0) {
                    Log.e("yanze", "this video size < 0 $path")
                    size = File(path).length() / 1024;
                }
                val displayName =
                    cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME))
                val modifyTime =
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED))

                val imageItem = ImageItem()
                imageItem.type = 1
                imageItem.name = displayName ?: ""
                imageItem.path = path
                imageItem.imageModifyDate = modifyTime
                imageItem.videoId = videoId
                imageItem.duration = duration
                videoList.add(imageItem)
                //按修改日期插入正确位置
                val targetIndex = allImages.indexOfFirst { it.imageModifyDate < imageItem.imageModifyDate }
                allImages.add(targetIndex, imageItem)
            }
        }
        Log.i("yanze","视频总数：${videoList.size}")
        Log.i("yanze","图片视频总数：${allImages.size}")
        resolverVideoCursor?.close()

        GlobalScope.launch(Dispatchers.Main) {
            albumAdapter.datas.clear()
            albumAdapter.datas.addAll(allImages)
            albumAdapter.notifyDataSetChanged()
        }
    }

    fun queryImageAndVideo() {
        //查询条件
        var where =
            MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Video.Media.MIME_TYPE + "=?" +
                    " or " + MediaStore.Video.Media.MIME_TYPE + "=?"
        Log.i("yanze", "where:${where}")
        var whereArgs = arrayOf(
            "image/jpeg", "image/png",
            "video/mp4"
        )
        var projection = arrayOf(
            MediaStore.Images.Media.DISPLAY_NAME,
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.DATE_MODIFIED,
            MediaStore.Images.Media.WIDTH,
            MediaStore.Images.Media.HEIGHT,
            MediaStore.Images.Media.MIME_TYPE,

            MediaStore.Video.Thumbnails._ID,
            MediaStore.Video.Thumbnails.DATA,
            MediaStore.Video.Media.DURATION,
            MediaStore.Video.Media.SIZE,
            MediaStore.Video.Media.DISPLAY_NAME,
            MediaStore.Video.Media.DATE_MODIFIED
        )
        val resolverCursor = contentResolver.query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            projection,
            where,
            whereArgs,
            MediaStore.Images.Media.DATE_MODIFIED + " DESC"
        )
        resolverCursor?.use { cursor ->
            val allImages = ArrayList<ImageItem>()
            while (cursor.moveToNext()) {
                val imageMimeType =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE))
                val videoMimeType =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE))
                val imageItem = ImageItem()
                Log.i("yanze", "fileType: $imageMimeType  ${videoMimeType}")
                if (TextUtils.equals(imageMimeType, "video/mp4")) { //视频
                    val videoId = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID))
                    val path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA))
                    val duration =
                        cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media.DURATION))
                    var size =
                        cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.SIZE)) / 1024 //大小：kb
                    if (size < 0) {
                        Log.e("yanze", "this video size < 0 $path");
                        size = File(path).length() / 1024;
                    }
                    val displayName =
                        cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME))
                    val modifyTime =
                        cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED))
                    imageItem.type = 1
                    imageItem.name = displayName ?: ""
                    imageItem.path = ""
                    imageItem.imageModifyDate = modifyTime
                    imageItem.videoId = videoId
//                    imageItem.thumbBitmap = thumbBitmap
                } else { // 图片
                    val imageName =
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME))
                    val imagePath =
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
                    val imageDate =
                        cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED))
                    val imageWidth =
                        cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH))
                    val imageHeight =
                        cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT))
                    if (imageWidth == 0 || imageHeight == 0) {
                        continue
                    }
                    imageItem.type = 0
                    imageItem.name = imageName ?: ""
                    imageItem.path = imagePath ?: ""
                    imageItem.width = imageWidth
                    imageItem.height = imageHeight
                    imageItem.imageModifyDate = imageDate
                }
                allImages.add(imageItem)
            }
            resolverCursor.moveToFirst()
            resolverCursor.close()
            GlobalScope.launch {
                withContext(Dispatchers.Main) {
                    albumAdapter.datas.clear()
                    albumAdapter.datas.addAll(allImages)
                    albumAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    fun query() {
        val queryTask = GlobalScope.launch(Dispatchers.IO) {
            //查询条件
            var where =
                MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?"
            var whereArgs = arrayOf("image/jpeg", "image/png")

            val resolverCursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                IMAGE_PROJECTION,
                where,
                whereArgs,
                MediaStore.Images.Media.DATE_MODIFIED + " DESC"
            )
            resolverCursor?.use { cursor ->
                val allImages = ArrayList<ImageItem>()
                while (cursor.moveToNext()) {
                    //查询数据
                    val imageName =
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME))
                    val imagePath =
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
                    val imageDate =
                        cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED))
                    val imageWidth =
                        cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH))
                    val imageHeight =
                        cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT))
                    val imageMimeType =
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE))

                    if (TextUtils.equals(imageMimeType, "image/gif")) {
                        if (!true) {
                            continue
                        }
                    }

                    if (imageWidth == 0 || imageHeight == 0) {
                        continue
                    }

                    //封装实体
                    val imageItem = ImageItem()
                    imageItem.name = imageName ?: ""
                    imageItem.path = imagePath ?: ""
                    imageItem.width = imageWidth
                    imageItem.height = imageHeight
                    imageItem.imageModifyDate = imageDate
                    allImages.add(imageItem)

                    //根据父路径分类存放图片
                    val imageFile = File(imagePath)
                    val imageParentFile = imageFile.parentFile
                    val imageFolder = ImageFolder()
                    imageFolder.name = imageParentFile!!.name
                    imageFolder.path = imageParentFile.absolutePath

                    if (!imageFolders.contains(imageFolder)) {
                        val images = ArrayList<ImageItem>()
                        images.add(imageItem)
                        imageFolder.cover = imageItem
                        imageFolder.images = images
                        imageFolders.add(imageFolder)
                    } else {
                        imageFolders[imageFolders.indexOf(imageFolder)].images.add(imageItem)
                    }
                }
                //防止没有图片报异常
                if (cursor.count > 0 && allImages.size > 0) {
                    //构造所有图片的集合
                    val allImagesFolder = ImageFolder()
                    allImagesFolder.name = "全部图片"
                    allImagesFolder.path = "/"
                    allImagesFolder.cover = allImages[0]
                    allImagesFolder.images = allImages
                    imageFolders.add(0, allImagesFolder)  //确保第一条是所有图片
                }
                cursor.moveToFirst()
                cursor.close()
                GlobalScope.launch {
                    withContext(Dispatchers.Main) {
                        albumAdapter.datas.clear()
                        albumAdapter.datas.addAll(allImages)
                        albumAdapter.notifyDataSetChanged()
                    }
                }
            }
        }
    }

    /**
     * 获取手机中所有视频的信息
     */
    fun queryVideo() {
        GlobalScope.launch(Dispatchers.IO) {
            var proj = arrayOf(
                MediaStore.Video.Thumbnails._ID,
                MediaStore.Video.Thumbnails.DATA,
                MediaStore.Video.Media.DURATION,
                MediaStore.Video.Media.SIZE,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.DATE_MODIFIED
            )
            var resolverCursor = getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                proj,
                MediaStore.Video.Media.MIME_TYPE + "=?",
                arrayOf("video/mp4"),
                MediaStore.Video.Media.DATE_MODIFIED + " desc"
            )
            resolverCursor?.use { cursor ->
                val allImages = ArrayList<ImageItem>()
                while (cursor.moveToNext()) {
                    val videoId = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID))
                    val path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA))
                    val duration =
                        cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media.DURATION))
                    var size =
                        cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.SIZE)) / 1024 //大小：kb
                    if (size < 0) {
                        Log.e("yanze", "this video size < 0 $path");
                        size = File(path).length() / 1024;
                    }
                    val displayName =
                        cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME))
                    val modifyTime =
                        cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED))
                    //生成缩略图
                    val thumbBitmap = MediaStore.Video.Thumbnails.getThumbnail(
                        contentResolver,
                        videoId,
                        MediaStore.Video.Thumbnails.MINI_KIND,
                        null
                    )
                    //查询缩略图
                    var thumbCursor = contentResolver.query(
                        MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                        arrayOf(MediaStore.Video.Thumbnails._ID, MediaStore.Video.Thumbnails.DATA),
                        MediaStore.Video.Thumbnails.VIDEO_ID + "=?",
                        arrayOf("$videoId"),
                        null
                    )
                    var thumbPath = ""
                    while (thumbCursor?.moveToNext() == true) {
                        thumbPath =
                            thumbCursor.getString(cursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
                    }
                    thumbCursor?.close()
                    // 获取该视频的父路径名
                    var dirPath = File(path).getParentFile().getAbsolutePath()
                    // 封装实体
                    val imageItem = ImageItem()
                    imageItem.name = displayName ?: ""
                    imageItem.path = thumbPath ?: ""
                    imageItem.imageModifyDate = modifyTime
                    imageItem.videoId = videoId
//                    imageItem.thumbBitmap = thumbBitmap
                    allImages.add(imageItem)
                }
                cursor.close()
                GlobalScope.launch(Dispatchers.Main) {
                    albumAdapter.datas.clear()
                    albumAdapter.datas.addAll(allImages)
                    albumAdapter.notifyDataSetChanged()
                }
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        queryTask?.cancel()
    }

    inner class AlbumAdapter : RecyclerView.Adapter<AlbumAdapter.AlbumViewHolder>() {
        var datas = ArrayList<ImageItem>()

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): AlbumAdapter.AlbumViewHolder {
            var view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_album, parent, false)
            return AlbumViewHolder(view)
        }

        override fun onBindViewHolder(holder: AlbumAdapter.AlbumViewHolder, position: Int) {
            holder.bindView(datas[position])
        }

        override fun getItemCount() = datas.size

        inner class AlbumViewHolder(var view: View) : RecyclerView.ViewHolder(view) {
            fun bindView(data: ImageItem) {
                val iv_album = view.findViewById<ImageView>(R.id.iv_album)
                val tv_duration = view.findViewById<TextView>(R.id.tv_duration)

                when (data.type) {
                    0 -> {
                        Glide.with(iv_album.context)
                            .load(File(data.path))
                            .into(iv_album)
                        tv_duration.visibility = View.GONE
                    }
                    1 -> {
                        view.setOnClickListener {
                            PreViewActivity.open(this@AlbumActivity,data.path)
                        }
//                        val thumbBitmap = ThumbnailUtils.createVideoThumbnail(
//                            data.path,
//                            MediaStore.Video.Thumbnails.MICRO_KIND
//                        )
                        val thumbBitmap = MediaStore.Video.Thumbnails.getThumbnail(
                            App.getInstance().contentResolver,
                            data.videoId,
                            MediaStore.Video.Thumbnails.MINI_KIND,
                            null
                        )
                        Glide.with(iv_album.context)
                            .load(thumbBitmap)
                            .into(iv_album)
                        tv_duration.text = "${data.duration / 1000}"
                        tv_duration.visibility = View.VISIBLE
                    }
                }
            }
        }

    }


}






